package com.epc.easypurchase.activity.web


import android.os.Build
import android.view.KeyEvent
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.epc.easypurchase.R
import com.woochen.baselibrary.base.mvp.BaseMvpActivity
import com.woochen.baselibrary.util.StatusBarUtil
import kotlinx.android.synthetic.main.activity_common_web_view.*

/**
 * 基类webview
 *
 * @author woochen
 * @time 2018/8/31 10:27
 */
abstract class BaseWebViewActivity : BaseMvpActivity() {



    override fun setContentView(): Int {
        return R.layout.activity_common_web_view
    }

    override fun initData() {
        showLoading(false)
        StatusBarUtil.setStatusBarFullTransparent(this)
        StatusBarUtil.StatusBarLightMode(this)
        initWebView()
    }

    /**
     * 初始化webview
     */
    private fun initWebView() {
        web.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                showContent()
            }

            override fun onLoadResource(view: WebView, url: String) {
                super.onLoadResource(view, url)
                //                LogUtil.e(TAG, "onLoadResource: " + url);
                loadResource(view, url)
            }

        }
        val webSettings = web.settings
        webSettings.javaScriptEnabled = true
        web.addJavascriptInterface(this, "android")
        // 支持缩放(适配到当前屏幕)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//少于4.4（不包括4.4）用这个
            webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        }
        //适应屏幕，大于等于4.4用这个
        webSettings.useWideViewPort = true
        webSettings.setSupportZoom(true)
        webSettings.loadWithOverviewMode = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不缓存
        web.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                //                LogUtil.e(TAG, "onReceivedTitle: " + title);
                receiveTitle(title)
            }
        }
    }

    /**
     * web中title标题
     *
     * @param title
     */
    protected fun receiveTitle(title: String) {
        setTitle(title)
    }


    /**
     * 拦截url
     *
     * @param view
     * @param url
     */
    protected fun loadResource(view: WebView, url: String) {

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack()) {
            web.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun back() {
        if (web.canGoBack()) {
            web.goBack()
        } else {
            finish()
        }
    }


}
